<template>
  <view class="editor-container">
    <!-- 编辑器主体 -->
    <editor ref="editor" />
    
    <!-- 颜色盘（通过 v-show 控制显示/隐藏） -->
    <view 
      class="color-picker" 
      v-show="showColorPicker"
      @click.stop> <!-- 阻止冒泡，避免点击颜色盘内部时关闭 -->
      <!-- 颜色选项 -->
      <view class="color-option" v-for="color in colors" :key="color" 
            :style="{ backgroundColor: color }" 
            @click="selectColor(color)"></view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      showColorPicker: false,
      colors: ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF']
    }
  },
  mounted() {
    // 监听全局点击事件
    document.addEventListener('click', this.handleOutsideClick);
  },
  beforeDestroy() {
    // 移除监听，避免内存泄漏
    document.removeEventListener('click', this.handleOutsideClick);
  },
  methods: {
    // 显示颜色盘
    toggleColorPicker() {
      this.showColorPicker = !this.showColorPicker;
    },
    
    // 选择颜色
    selectColor(color) {
      this.editorCtx.format('color', color);
      this.showColorPicker = false; // 选择颜色后关闭
    },
    
    // 处理外部点击
    handleOutsideClick(event) {
      const colorPicker = this.$el.querySelector('.color-picker');
      
      // 如果颜色盘不存在或未显示，直接返回
      if (!colorPicker || !this.showColorPicker) return;
      
      // 判断点击是否在颜色盘外部
      if (!colorPicker.contains(event.target)) {
        this.showColorPicker = false;
      }
    }
  }
}
</script>